package com.codingstudy.login.advice;

import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @Author: wangzhengsheng@supcon.com
 * @Create: 2021/7/20 15:23
 */
@RestControllerAdvice
public class SpringExceptionHandler {
//
//    /**
//     * 全局处理Exception
//     * 错误的情况下返回500
//     * @param ex
//     * @param req
//     * @return
//     */
//    @ExceptionHandler(value = {Exception.class})
//    public ResponseEntity<Object> handleOtherExceptions(final Exception ex, final WebRequest req) {
//        return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//    }


    @ModelAttribute
    public void addAttributes(Model model , HttpServletRequest http, ModelMap modelMap) throws ServletException, IOException, ClassNotFoundException {
        Enumeration<String> parameterNames = http.getParameterNames();
        System.out.println(parameterNames);
        Map<String, String[]> parameterMap = http.getParameterMap();
        for(Map.Entry<String,String[]> entry: parameterMap.entrySet()){
            System.out.println("key:"+ entry.getKey());
            for (int i = 0; i < entry.getValue().length; i++) {
                System.out.println("value:"+ entry.getValue()[i]);
            }
        }




        /*
         * 通过读取流的方式获取请求参数，但是流的话只能读取一次  如果在这里操作的话，spring控制器里就接受不到参数了
         */
//        BufferedReader bufferReaderBody = null;
//        try {
//            bufferReaderBody = new BufferedReader(http.getReader());
//            String s;
//            StringBuffer postData = new StringBuffer();
//            while ( (s = bufferReaderBody.readLine())!=null){
//                postData.append(s);
//            }
//            System.out.println(postData.toString());
//        } catch (IOException e) {
//
//            throw e;
//
//        } finally {
//
//            if (bufferReaderBody != null) {
//                bufferReaderBody.close();
//            }
//        }model.addAttribute("words", "hello world");
    }

    @InitBinder
    public void globalInitBinder(WebDataBinder binder) {
        //前端传入的时间处理方式
        //binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));

    }
}
